package cn.icybear.orzjisp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;

import cn.icybear.orzjisp.compiler.CodeCompiler;
import cn.icybear.orzjisp.compiler.CompileException;
import cn.icybear.orzjisp.parser.CodeParser;
import cn.icybear.orzjisp.parser.ParseException;

public class OrzCompiler {
	public static void main(String args[]) throws ParseException,
			CompileException, IOException {
		String output = "a.orz";
		boolean debug = false;
		LinkedList<String> srcs = new LinkedList<String>();
		if (args.length == 0) {
			System.out.println("Usage: OrzCompiler [-o output] [-debug] file*");
			System.out.println("Default output file: " + output);
			return;
		}
		for (int i = 0; i < args.length; i++) {
			if (args[i].equalsIgnoreCase("-o")) {
				output = args[++i];
			} else if (args[i].equalsIgnoreCase("-debug")) {
				debug = true;
			} else {
				srcs.add(args[i]);
			}
		}
		OutputStream os = new BufferedOutputStream(new FileOutputStream(output));
		CodeParser parser = null;
		CodeCompiler cc = new CodeCompiler();
		Expression head = null, tail = null, temp = null;
		for (String src : srcs) {
			InputStream input = new BufferedInputStream(
					new FileInputStream(src));
			if (parser == null) {
				parser = new CodeParser(input);
			} else {
				parser.ReInit(input);
			}
			System.out.println("Compile " + src);
			temp = parser.getHead();
			if (head == null) {
				head = temp;
				tail = CodeParser.getTail(temp);
			} else {
				tail.next = temp;
				tail = CodeParser.getTail(temp);
			}
//			System.out.println("Done compile.");
			input.close();
		}
		System.out.println("Done compile, linking...");
		String s = cc.compile(os, head);
		if (debug)
			System.out.println(s);
		os.flush();
		os.close();
	}
}
